package com.clarence.dada.core.auth.jwt;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.clarence.dada.core.auth.expander.AuthConfigExpander;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.Map;

/**
 * <p>
 * jwt生成工具
 * <p>
 *
 * @author <a href="mailto:1093776034@qq.com">GD</a>
 * @since 2024/2/20 14:28
 */
public class JwtTokenUtil {


    public static String generateTokenDefaultPayload(DefaultJwtPayload defaultJwtPayload) {

        // 计算过期时间
        DateTime expirationDate = DateUtil.offsetSecond(new Date(), Convert.toInt(AuthConfigExpander.getAuthJwtTimeoutSeconds()));

        // 设置过期时间
        defaultJwtPayload.setExpirationDate(expirationDate.getTime());

        // 构造jwt token
        return Jwts.builder()
                .setClaims(BeanUtil.beanToMap(defaultJwtPayload))
                .setSubject(defaultJwtPayload.getUserId().toString())
                .setIssuedAt(new Date())
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, AuthConfigExpander.getAuthJwtSecret())
                .compact();
    }
//
//    @Override
//    public DefaultJwtPayload getDefaultPayload(String token) {
//        Map<String, Object> jwtPayload = Jwts.parser()
//                .setSigningKey(jwtConfig.getJwtSecret())
//                .parseClaimsJws(token)
//                .getBody().getJwtPayloadClaims(token);
//        return BeanUtil.toBeanIgnoreError(jwtPayload, DefaultJwtPayload.class);
//    }
}
